package org.hashdb.client.net.nio.msg;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hashdb.client.util.JsonService;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Date: 2024/1/16 21:20
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public abstract class Message<B> {
    private static final AtomicLong messageIdAccumulator = new AtomicLong(0);


    /**
     * 客户端的id为负数
     */
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    protected final long id;

    @Nullable
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    protected final B body;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    public abstract MessageMeta getMeta();

    /**
     * @param id   由协议层调用,实例化Message
     * @param body 要发送的详细数据
     */
    public Message(long id, @Nullable B body) {
        if (id > 0) {
            throw new IllegalArgumentException("id must be negative");
        }
        this.id = id;
        this.body = body;
    }

    public Message(@Nullable B body) {
        id = messageIdAccumulator.decrementAndGet();
        this.body = body;
    }

    public long id() {
        return id;
    }

    public @Nullable B body() {
        return body;
    }

    @Override
    public String toString() {
        return JsonService.toString(this);
    }
}
